package com.milk.controller.admin;

import com.github.pagehelper.PageHelper;
import com.milk.dto.MilkteaDTO;
import com.milk.dto.MilkteaPageQueryDTO;
import com.milk.entity.Milktea;
import com.milk.result.PageResult;
import com.milk.result.Result;
import com.milk.service.IMilkteaService;
import com.milk.vo.MilkteaVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController("adminMilkTea")
@RequestMapping("admin/milktea")
@Slf4j
@CrossOrigin
public class MilkteaController {
    @Autowired
    private IMilkteaService milkteaService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 奶茶分页查询
     * @param dto
     * @return
     */
    @GetMapping("/pageQuery")
    public Result<PageResult> pageQuery(MilkteaPageQueryDTO dto){
        log.info("分页查询的内容 = {}",dto);
        PageResult pageResult = milkteaService.selectPageQuery(dto);
        return Result.success(pageResult);
    }

    /**
     * 新增奶茶
     * @param milkteaDTO
     * @return
     */
    @PostMapping("/insert")
    public Result insertMilktea(@RequestBody MilkteaDTO milkteaDTO){
        log.info("新增奶茶 = {}",milkteaDTO);
        milkteaService.insertMilktea(milkteaDTO);
        //清除缓存
        clenCache("milkteaCategory_"+milkteaDTO.getCategoryId());
        return Result.success();
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping("/{ids}")
    public Result deleteByIds(@PathVariable List<Long> ids){
        log.info("批量删除的id = {}",ids);
        milkteaService.deleteByIds(ids);
        //清除缓存
        clenCache("milkteaCategory_*");
        clenCache("milktea_*");
        return Result.success();
    }

    /**
     * 更新奶茶信息
     * @param milkteaDTO
     * @return
     */
    @PostMapping("/updata")
    public Result updataMilktea(@RequestBody MilkteaDTO milkteaDTO){
        log.info("修改奶茶信息 = {}",milkteaDTO);
        milkteaService.updataMilktea(milkteaDTO);
        //清除缓存
        clenCache("milkteaCategory_*");
        clenCache("milktea_*");
        return Result.success();
    }

    @GetMapping("/selectById/{id}")
    public Result<MilkteaVO> selectById(@PathVariable Long id){
        MilkteaVO milkteaVO = milkteaService.selectById(id);
        return Result.success(milkteaVO);
    }

    // 清除缓存
    public void clenCache(String pattern){

        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

}
